<template>
  <!-- 新增对话框 -->
  <el-dialog
    :title="form.id ? '修改参数配置' : '新增参数配置'"
    :visible.sync="dialogVisible"
    width="40%"
    >
    <el-form ref="form" :model="form" label-width="80px">
      <el-form-item label="类别名称" prop="name"
        :rules="[
        { required: true, message: '类别名称不能为空'}
      ]">
        <el-input v-model="form.name"></el-input>
      </el-form-item>
      <el-form-item label="上级ID" style="text-align:left" prop="pid">
        <treeselect
        v-model="form.pid"
        :clearable="true"
        placeholder="请选择上级ID"
        noChildrenText="不好意思哟~,没有下一级了~~"
        :normalizer="normalizer"
        :options="options"/>
      </el-form-item>
      <el-form-item label="排序" style="text-align:left;" prop="sort">
        <el-input-number v-model="form.sort" :min="1"></el-input-number>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="handleSubmit">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { getDiseaseCategoryById, addorupdateDisease } from '@/api/hospital/index'
export default {
  props: {
    options: {
      type: Array,
      default: () => []
    },
  },
  data () {
    return {
      dialogVisible: false,
      isAdd: true,
      form: {
        id: '',
        name: '',
        pid: '0',
        sort: 1
      },
      normalizer(node) {
        return {
          label: node.name
        }
      },
    }
  },
  components: {
    Treeselect
  },
  methods: {
    // 初始化
    init (id, type) {
      // 清空数据
      this.form.id = ''
      if (this.$refs.form !== undefined) {
        this.$refs.form.resetFields()
      }
      if (type === 'add') { // 新增
        // 填充父级ID
        if (id) this.form.pid = id
      } else { // 修改
        // 根据id 获取单单条数据
        getDiseaseCategoryById({id: id})
        .then(res => {
          if (res.code === 200) {
            // 数据回显
            this.form = { ...res.data }
          }
        })
      }
      this.dialogVisible = true
    },
    // 提交数据
    handleSubmit() {
      // 验证表单
      this.$refs.form.validate((valid) => {
        if (valid) {
          // 提交数据
          addorupdateDisease({...this.form})
          .then(res => {
            if (res.code === 200) {
              // 关闭对话框
              this.dialogVisible = false
              // 刷新列表
              this.$emit('refreshFun')
            }
          })
        }
      })
    }
  }
}
</script>
